package com.atguigu.gmall.realtime.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author lvbingbing
 * @date 2022-06-28 22:53
 */
@Slf4j
public class DateUtils {

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private DateUtils() {
    }

    /**
     * 将日期类型转换成字符串
     * <p>
     *
     * @param date <br>
     * @return yyyy-MM-dd HH:mm:ss 格式的日期字符串
     */
    public static String formatDate(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return DTF.format(localDateTime);
    }

    /**
     * 将字符串日期转换为时间毫秒数
     *
     * @param dateString yyyy-MM-dd HH:mm:ss 格式的日期字符串
     * @return 时间毫秒数
     */
    public static Long getTimestamp(String dateString) {
        LocalDateTime dateTime = LocalDateTime.parse(dateString, DTF);
        return dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 根据生日获取年龄
     *
     * @param birthDay 生日字符串
     * @param pattern  日期格式
     * @return 年龄
     */
    public static int getAge(String birthDay, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return getAge(sdf.parse(birthDay));
        } catch (ParseException e) {
            log.error("根据生日获取年龄出现异常！入参日期：{}, 日期格式：{}, 异常原因：{}", birthDay, pattern, e);
            return 0;
        }
    }

    /**
     * 根据生日获取年龄
     *
     * @param birthDay 生日
     * @return 年龄
     */
    public static int getAge(Date birthDay) {
        int age;
        Calendar cal = Calendar.getInstance();
        // 出生日期晚于当前时间，无法计算
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        // 当前年份
        int yearNow = cal.get(Calendar.YEAR);
        // 当前月份
        int monthNow = cal.get(Calendar.MONTH);
        // 当前日期
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        // 计算年龄
        age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    // 当前日期在生日之前，年龄减一
                    age--;
                }
            } else {
                // 当前月份在生日之前，年龄减一
                age--;
            }
        }
        return age;
    }
}